﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MobilesStore.Domain.Entities
{
    public class Cart
    {
        private List<CartLine> LineCollection = new List<CartLine>();

        public void AddItem(Product product, int Quantity)
        {
            CartLine line = LineCollection.Where(l => l.Product.ProductID == product.ProductID)
                .FirstOrDefault();
            if (line == null)
            {
                LineCollection.Add(new CartLine
                {
                    Product = product,
                    Quantity = Quantity
                });
            }
            else {
                line.Quantity += Quantity;
            }
        }

        public void RemoveLine(Product product)
        {
            LineCollection.RemoveAll(l => l.Product.ProductID == product.ProductID);
        }

        public decimal ComputeTotalValue()
        {
            if (lines.Count() != 0)
            {
                return LineCollection.Sum(l => l.Product.ProductPrice * l.Quantity);
            }
            else {
                return 0;
            }
        }

        public void Clear()
        {
            LineCollection.Clear();
        }

        public IEnumerable<CartLine> lines {
            get { return LineCollection; }
        }

        public decimal ComputeCartlineValue(CartLine line)
        {
            return (line.Product.ProductPrice * line.Quantity);
        }

        public decimal ComputeSubValue(float percent)
        {
            return Math.Round(ComputeTotalValue() * (decimal)percent,2);
        }
    }

    public class CartLine
    {
        public Product Product { get; set; }
        public int Quantity { get; set; }
    }
}
